<?php
namespace common\models;

use Yii;
use yii\base\Model;
use common\models\User;

/**
 * Login form
 */
class PasswordForm extends Model
{
    public $curpwd;
    public $newpwd;
    public $repwd;

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['curpwd', 'newpwd', 'repwd'], 'required'],
            [['newpwd','repwd'], 'string', 'min' => 6],
            ['repwd', 'compare', 'compareAttribute' => 'newpwd','message'=>'两次输入的密码不一致！'],
        ];
    }

    public function password($id)
    {
        if (!$this->validate()) {
            return null;
        }
        
        $model = User::find()->where("ID = $id")->one();
        if(Yii::$app->security->validatePassword($this->curpwd, $model->password_hash))
        {
            // echo '旧密码正确';
            $model->setPassword($this->newpwd);
            return $model->save();
        }
        else
        {
            // echo '旧密码错误';
            Yii::$app->session->setFlash('error', '旧密码错误');
        }
    }

    public function attributeLabels()
    {
        return [
            'curpwd' => '当前密码',
            'newpwd' => '新密码',
            'repwd' => '确认新密码',
        ];
    }
}